package main

import (
	"fmt"
	"reflect"
)

type Person struct {
	Name   string `json:"name"`
	Age    int    `json:"age"`
	Gender string `json:"gender"`
}

func main() {
	p := Person{
		Name:   "Allen.Wu",
		Age:    25,
		Gender: "male",
	}

	getValue := reflect.ValueOf(p)
	getType := reflect.TypeOf(p)
	fmt.Printf("type: %v, value: %v\n", getType, getValue)

	getTypePtr := reflect.TypeOf(&p)
	typeElem := getTypePtr.Elem()
	fmt.Printf("type: %v, typeElem: %v\n", getTypePtr, typeElem)

	// 遍历结构体的字段
	// tag 属于结构体的元信息，可以在运行的时候通过反射的机制获取到
	// reflect.TypeOf()
	for i := 0; i < getValue.NumField(); i++ {
		fieldValue := getValue.Field(i)
		fieldType := getType.Field(i)

		fmt.Printf("fieldValue.Type():%v\n", fieldValue.Type()) // string
		fmt.Printf("fieldType.Type():%v\n", fieldType.Type)     // string

		fmt.Printf("name: %s value: %v, tag: %v\n\n", fieldType.Name,
			fieldValue.Interface(), fieldType.Tag.Get("json"))
	}
}

/*

type: main.Person, value: {Allen.Wu 25 male}
fieldValue.Type():string
fieldType.Type():string
name: Name value: Allen.Wu, tag: name

fieldValue.Type():int
fieldType.Type():int
name: Age value: 25, tag: age

fieldValue.Type():string
fieldType.Type():string
name: Gender value: male, tag: gender

*/
